package com.cilico.single.components;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Stack;
import java.util.Vector;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.method.PasswordTransformationMethod;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.cilico.single.ConfigManager;
import com.cilico.single.Mid;
import com.cilico.single.R;
import com.cilico.single.components.Select.Option;
import com.cilico.single.shopcart.ShopCart;
import com.cilico.single.shopcart.ShopCartList;
import com.cilico.single.utils.PackageManagerAndroid;
import com.cilico.single.utils.Utils;
import com.cilico.single.view.BaseView;
import com.cilico.single.view.Channel;
import com.cilico.single.view.FormAction;
import com.cilico.single.view.FormLayout;
import com.cilico.single.view.HelpView;
import com.cilico.single.view.SegmentLinearLayout;
import com.cilico.single.view.UserManager;
import com.cilico.single.waterfall.Waterfall;
/**
 * 解析类。用于报文解析及控件生成
 * Parser for all of our Atom feeds.
 */
public final class AtomParser extends DefaultHandler {
    boolean isChecked_;
    boolean isHasValue_; // 判断节点是否有值
    boolean skipDiv; // 判断是否跳过DIV解析
    boolean PTag_ = false; // 判断是否为 <P>标签
    int parseType_; // 需要载入的解析方法类型
    int eventType_; // 出发的事件类型
    int readTextIndex_; // 读取中间节点值的次数
    public final int START_DOCUMENT = 0;
    public final int END_DOCUMENT = 1;
    public final int START_TAG = 2;
    public final int END_TAG = 3;
    public final int TEXT = 4;
    public final static int parseHelp_ = 0; // 解析帮助页面
    public final static int parseLoginResult_ = 1; // 解析登陆结果
    public final static int parseChannelListing_ = 2; // 解析频道列表
    public final static int parsekXMLItems_ = 3;
    public final static int parseOnePOI_ = 4; // 解析一个详细页面
    public final static int parsePOI_ = 5;
    StringBuffer buf_ = new StringBuffer(); // 存储节点值
    BaseView activity_;
    HelpView help_;
    ParseHtml htmlItem_;
    ChannelRepository repo_; // 保存channel，如二级菜单等
    ParseHtml.LayoutState ls_;
    Channel channel_;
    Channel tempChannel_; // 临时变量
    static Channel channelYHGG_;
    POI poi_; // 网点地图
    ChannelParam p_;
    UserManager um_;
    Table table_;
    Attributes atts_;
    boolean selectSave_; // 下拉框控件save属性
    boolean selectTrueSave_; // 下拉框控件truesave属性
    SegmentLinearLayout sll_;
    String accessory_; // 下拉框控件accessory属性
    String workspaceTitle_;
    String userInfo_;
    String seniorID_;
    String name_;
    String rname_;
    String label_;
    String value_;
    String type_;
    // 输入框提示文字及属性
    String placeholder_;
    String selectSort_;
    String sortKey_;
    String fillType_;
    StringBuffer underscores_;
    String select_;
    String nodeName_;
    String selectUrl_;
    String selectIcon_;
    String selectForm;
    String selectName_;
    Vector<POI> poiList_;
    String group_;
    String ref_;
    String[] relaEnable_; // 联动：enable
    String[] relaDisable_;// 联动：disable
    String[] relaVisible_;// 联动：可见
    String[] relaInvisible_;// 联动：不可见
    private Mid mid_;
    String lastElementName_;
    Stack<String> stack_;
    private String id_;
    private String style_;
    private String cla_;
    private String name;
    Vector<Option> options_; // 下拉框控件中的Option集合
    private String inputType_; // <input>类型
    private String titleBarTitle_ = null;
    private String rightButton_ = null;
    private String leftButton_ = null;
    private int textFiedCount_ = 0;//记录一次解析过程中输入框的个数，在setTag的时候加上此序号
    
    /**
     *  解析文件时调用此方法
     */
    public void startDocument() throws SAXException {
        try {
        	textFiedCount_ = 0;
            stack_ = new Stack<String>();
            eventType_ = START_DOCUMENT;
            PTag_ = false;
            Utils.hiddenTitleBar_ = false;
            BaseView.updateTable_ = false;
            BaseView.istimeout_ = false;
			if (BaseView.ttimerIscannel_) {
				ConfigManager.currentView_.vWidgetArray_ = null;
				ConfigManager.currentView_.vWidgetArray_ = new Vector<Object>();
				ConfigManager.currentView_.cmpList_ = null;
				ConfigManager.currentView_.cmpList_ = new ArrayList<Component>();
				ConfigManager.currentView_.invisibleViews_ = null;
				ConfigManager.currentView_.invisibleStyles_ = null;
			}
            sll_ = null;
            titleBarTitle_ = null;
            rightButton_ = null;
            leftButton_ = null;
            switch (parseType_) {
            case parseOnePOI_:
                poi_ = new POI();
                break;
            case parsePOI_:
                break;
            case parsekXMLItems_:
                break;
            }
        } catch (Exception e) {
            Utils.printException(e);
        }
    }

    // XML开始解析结束时调用此方法
    public void endDocument() throws SAXException {
        try {
            eventType_ = END_DOCUMENT;
            PTag_ = false;
			switch (parseType_) {
			case parsekXMLItems_:
				htmlItem_.addLsItem(activity_);
				if (htmlItem_.imageUrlRemote_ != null && htmlItem_.imageUrlRemote_.size() > 0) {
					htmlItem_.downloadImageFromRemote();
				}
				if (!(BaseView.updateTable_ && BaseView.ttimerIscannel_)) {
					activity_.runOnUiThread(new Runnable() {
						public void run() {
							if (titleBarTitle_ != null) {
								activity_.titleBar_.resetTitleBarContent(2, titleBarTitle_, leftButton_, rightButton_);
							} else if (activity_.titleBar_ != null){
								activity_.titleBar_.resetTitleBarContent(1, "", null, "exit");
							}
							activity_.cmpList_ = htmlItem_.cmps_;
							activity_.appendComponents(htmlItem_.cmps_);
							if (!BaseView.updateTable_) {
								if (htmlItem_.imagesUrl_ != null && htmlItem_.imagesUrl_.size() > 0) {
									htmlItem_.downloadImageFromServer();
								}
								// 根据xml文档设置控件的可见不可见等属性
								Utils.settleComponets(activity_);
								Utils.isAtTheBottom(activity_);
							}
						}
					});
				} else {
					BaseView.timerIsRunning_ = false;
				}
                break;
            }
        } catch (Exception e) {
            Utils.printException(e);
            BaseView.timerIsRunning_ = false;
        }
        accessory_ = null;
        
    }


    // 解析到Element的开头时调用此方法
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        try {
            // 将节点名推入棧
            stack_.push(localName);
            // 得到棧里面最后一个节点名
            if ((null != stack_) && (!stack_.isEmpty()))
                lastElementName_ = (String) stack_.peek();
            eventType_ = START_TAG;

            // 赋值节点属性
            atts_ = atts;
            // 将读取节点值次数标记复位
            readTextIndex_ = 0;
            
            switch (parseType_) {
            case parseHelp_:
                break;
            case parseLoginResult_:
                parseLoginResult(localName);// 解析九宫格
                break;
            case parseChannelListing_:// 解析tab
                parseChannelListing(localName);
                break;
            case parsekXMLItems_:// 解析html
                checkText();
                parsekXMLItems(localName);
                break;
            case parseOnePOI_:// 解析一个poi
                parseOnePOI(localName);
                break;
            case parsePOI_:// 解析poi列表 现在暂时没有了
                parsePOI(localName);
                break;
            }
        } catch (Exception ex) {
            Utils.printException(ex);
        }
    }

    // 解析到Element的结尾时调用此方法
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    	eventType_ = END_TAG;
        try {
            String content = "";
            if (null != buf_) {
                content = buf_.toString().trim();
                content = Utils.insteadOfSpecillCharacter(content, false);
                //存储用户名和用户ID
                if (localName.equals("userName") || localName.equals("userId")) {
                	String userName = BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.USER_NAME);
                	String userId = BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.RESTAURANT_USER_ID);
                	if (localName.equals("userName")) {
                		if (userName == null || userName.trim().equalsIgnoreCase("")) {
                			BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.USER_NAME, content);
						}
                	}
                	if (localName.equals("userId")) {
                		if (userId == null || userId.trim().equalsIgnoreCase("")) {
                			BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.RESTAURANT_USER_ID, content);
						}
                	}
				}
            }
            // 得到棧里面最后一个节点名
            if ((null != stack_) && (!stack_.isEmpty()))
                lastElementName_ = (String) stack_.peek();
            switch (parseType_) {
            case parseHelp_:
                parseHelp(localName);
                break;
            case parseLoginResult_:
                parseLoginResult(localName);
                break;
            case parseChannelListing_:
                parseChannelListing(localName);
                break;
            case parsekXMLItems_:
                checkText();
                parsekXMLItems(localName);
                break;
            case parseOnePOI_:
                parseOnePOI(localName);
                break;
            case parsePOI_:
                parsePOI(localName);
                break;
            }
            // 还原节点是否有值标记位
            isHasValue_ = false;
            buf_ = null;
        } catch (Exception e) {
            Utils.printOutToConsole("AtomParser-endElement-e" + e.toString());
        }
        if ((null != stack_) && (!stack_.isEmpty()))
            stack_.pop();
    }

    private void checkText() {

        if (skipDiv) {
            return;
        }

        boolean isNormal = true;
        int indexSelect = stack_.indexOf("select");
        int indexOption = stack_.indexOf("option");
        if ((indexSelect != -1) && (indexOption != -1) && (indexSelect < indexOption)
                && lastElementName_.equalsIgnoreCase("option")) {
            // 节点正处于"opteion"节点内，且为select的字节点，表示正解析下拉框控件.由于原始的解析方法在该处是不要执行此操作，所以特作此标记位

            isNormal = false;
        } else if (!isHasValue_) {
            // 如果节点名为空，则不执行该方法的剩余部分
            isNormal = false;
        } else if (stack_.peek().toString().equalsIgnoreCase("label")) {
            // 如果节点名为Label，同样不执行以下方法
            isNormal = false;
        } else if (stack_.peek().toString().equalsIgnoreCase("style")) {
            // 如果节点名为style，同样不执行以下方法
            isNormal = false;
        }
        // 复位节点值有无判断标志，一个节点只运行一次该方法，最多
        isHasValue_ = false;
        try {
            if (isNormal) {
				// 防止制表符
				String buf = buf_.toString().replaceAll("	", "");
				if ((null == buf) || (buf.trim().equals("")))
					return;
				String text = buf.toString().trim();

                Utils.printOutToConsole("-----" + text);
                if (PTag_ && text != null && text.trim().length() > 0) {
                    String string = text;
                    if (string.indexOf("  ") != 0) {
                        int w = (int) htmlItem_.ls_.font_.measureText("国国");
                        int l = (int) (w / htmlItem_.ls_.font_.measureText(" ") + (w
                                % htmlItem_.ls_.font_.measureText(" ") == 0 ? 0 : 1));
                        for (int i = 0; i < l; i++)
                            string = " ".concat(string);
                    }
                    text = string;
                }

                if (text != null && text.trim().length() > 0) {
                    htmlItem_.textInForm_ = text;
                }
            }
        } catch (Exception e) {
            Utils.printOutToConsole(e.toString());
        }
    }

    // 设置解析Help时的需要属性
    public void setParseHelpProperty(int parseType, HelpView help) {
        parseType_ = parseType;
        help_ = help;
    }

    // 设置解析LoginResult时的需要属性
    public void setLoginResultProperty(int parseType, UserManager um, ChannelRepository repo, String seniorID) {
        parseType_ = parseType;
        um_ = um;
        repo_ = repo;
        seniorID_ = seniorID;
    }

    // 设置解析ChannelListingProperty时的需要属性
    public void setChannelListingProperty(int parseType, ChannelRepository repo, String seniorID) {
        parseType_ = parseType;
        repo_ = repo;
        seniorID_ = seniorID;
    }

    // 设置解析UsingkXML是需要的属性
    public void setUsingkXMLProperty(int parseType, BaseView activity) {
        parseType_ = parseType;
        activity_ = activity;
    }

    // 设置解析POI时的需要属性
    public void setPOIProperty(int parseType, Vector<POI> poiList, Channel channel) {
        parseType_ = parseType;
        poiList_ = poiList;
        channel_ = channel;
    }

    // 设置解析一个POI时需要的属性
    public void setOnePOIProperty(int parseType, BaseView activity) {
        parseType_ = parseType;
        activity_ = activity;
    }

    // 设置解析CSSInLine时的需要属性
    public void setCSSInLineProperty(int parseType, ParseHtml.LayoutState ls) {
        parseType_ = parseType;
        ls_ = ls;
    }

    // 设置解析Span时的需要属性
    public void setSpanProperty(int parseType, Table table) {
        parseType_ = parseType;
        table_ = table;
    }

    // 设置解析ReadChannel时的需要属性
    public void setReadChannelProperty(int parseType, ChannelRepository repo, String workspaceTitle, String userInfo,
            String seniorID) {
        parseType_ = parseType;
        repo_ = repo;
        workspaceTitle_ = workspaceTitle;
        userInfo_ = userInfo;
        seniorID_ = seniorID;
    }

    // 设置解析ChannelProperties时的需要属性
    public void setReadChannelPropertiesProperty(int parseType, Channel channel) {
        parseType_ = parseType;
        channel_ = channel;
    }

    // 设置解析ReadOneChannelParam时的需要属性
    public void setReadOneChannelParamProperty(int parseType) {
        parseType_ = parseType;
    }

    // 设置解析ReadOnePoi时的需要属性
    public void setReadOnePoiProperty(int parseType) {
        parseType_ = parseType;
    }

    // 设置解析ReadOnePoiProperty时的需要属性
    public void setReadOnePoiPropertyProperty(int parseType, POI poi) {
        parseType_ = parseType;
        poi_ = poi;
    }

    // 设置解析ReadSelectValues时的需要属性
    public void setReadSelectValuesProperty(int parseType, ChannelParam p) {
        parseType_ = parseType;
        p_ = p;
    }

    // 设置解析ReadWorkSpace?��的需要属性
    public void setReadWorkSpaceProperty(int parseType, ChannelRepository repo, String seniorID) {
        parseType_ = parseType;
        repo_ = repo;
        seniorID_ = seniorID;
    }

    public void setkXMLItemsProperty(int parseType, BaseView bv) {
        parseType_ = parseType;
        activity_ = bv;
        htmlItem_ = new ParseHtml(activity_, mid_);
        underscores_ = new StringBuffer();
        int cw = (int) htmlItem_.ls_.font_.measureText(String.valueOf('_'));

        for (int i = 0; i < (activity_.preferredItemTextWidth() / cw); i++) {
            underscores_.append("_");
        }
        activity_.blackView_ = 0; // default value is 0;
    }

    // 取得一个解析好的POI对象
    public POI getOnePOI() {
        return poi_;
    }

    // 取得一个解析好的Channel对象
    public Channel getChannel() {
        return channel_;
    }

    // 取得Element的中间夹的字符串
    public void characters(char ch[], int start, int length) {

        if (eventType_ == END_TAG && length > 1) {
            // 如果紧接着end_tag后面有需要获取出来的数据则执行
            readTextIndex_ = 0;
        }
        try {
            eventType_ = TEXT;
            PTag_ = false;
            if (readTextIndex_ == 0) {
                // 节点计数器为零表示是第一次读取该节点值。应将以前读取的值全部清空。该处执行赋空操作，如果执行delete操作数据量大的话会引起内存溢出问题。
                buf_ = null;
                buf_ = new StringBuffer();
                // 该判断条件保证每个节点只进入一次，可以规避从子节点返回父节点也要执行该方法带来的不便。
                // 进入该方法表示该节点有值（存在子节点或者存在节点值）
                // 进入每个节点都会进入该判断条件
                isHasValue_ = true;
            }
            // 读取节点值
            if (null != buf_)
                buf_.append(ch, start, length);
            // 节点值计数器累加
            readTextIndex_++;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    public AtomParser(Mid mid) {
        super();
        mid_ = mid;
    }

    private void parseChannelListing(String localName) throws Exception {
        if (eventType_ == START_TAG) {
            if (localName.equalsIgnoreCase("workspace")) {

                workspaceTitle_ = getAttrString("title");
                repo_.addWorkspace(workspaceTitle_);
            } else if (localName.equalsIgnoreCase("collection")) {
                channel_ = new Channel(repo_);
                channel_.setWorkspace(workspaceTitle_);
                channel_.setUserid(userInfo_);
                channel_.setSeniorID(seniorID_);
                channel_.setTitle(getAttrString("title"));
                if (userInfo_ != null && !userInfo_.equals("0")){
//                	channel_.setStore("yes");
                }
                channel_.setUrl(getAttrString("href"));
                channel_.setChannelUrl(getAttrString("url"));
            } else if (localName.equalsIgnoreCase("param")) {
                p_ = readOneChannelParam(localName);
                channel_.addParam(p_);
            } else if (localName.equalsIgnoreCase("select")) {
                p_ = readOneChannelParam(localName);
                p_.type_ = "select";
                channel_.addParam(p_);
            } else if (localName.equalsIgnoreCase("option")) {
                String value = getAttrString("label");
                String label = getAttrString("value");
                String select = getAttrString("selected");
                if (select != null)
                    p_.value_ = value;
                p_.setSelectValues(value, label);
            }  
            
        } else {
            String text = "";
            if (null != buf_)
                text = buf_.toString().trim();
            if (localName.equalsIgnoreCase("workspace")) {
                if (getLevel("workspace") == 2) {
                    channel_ = new Channel(repo_);
                    channel_.setWorkspace(workspaceTitle_);
                    channel_.setUserid(userInfo_);
                    channel_.setSeniorID(seniorID_);
                    channel_.setTitle(getAttrString("title"));
                    channel_.setUrl(getAttrString("href"));

                    channel_.isCollection_ = true;
                    repo_.addChannel(channel_);
                }
            } else if (localName.equalsIgnoreCase("current_page")) {
                repo_.getPaging().setCurrentPage(Integer.parseInt(text));
            } else if (localName.equalsIgnoreCase("last_page")) {
                repo_.getPaging().setLastPage(Integer.parseInt(text));
            } else if (localName.equalsIgnoreCase("user")) {
                userInfo_ = text;
            } else if (localName.equalsIgnoreCase("collection")) {
                repo_.addChannel(channel_);
            } else if (localName.equalsIgnoreCase("id")) {
                channel_.setId(text);
            } else if (localName.equals("type")) {
                channel_.setFeedType(text);
            } else if (localName.equals("query")) {
                channel_.initAddQueryHistory(text);
            } else if (localName.equals("logo")) {
                channel_.logoUrl_ = text;
            } else if (localName.equals("shortcut")) {
                channel_.shortCut_ = text;
            } else if (localName.equals("selecturl")){
            	if (text != null && !text.equals("")){
            		channel_.setChannelSUrl(text);
            	}
            } else if (localName.equals("funid")){
            	if (text != null && !text.equals(""))
            		channel_.setChannelFunId(text);
            } else if (localName.equals("name")){
            	if (text != null){
            		channel_.setChannelName(text);
            	}
            } 
        }
    }

    // 得到xml相同元素名节点嵌套层级
    private int getLevel(String elementName) {
        // TODO Auto-generated method stub
        int level = 0;
        int size = stack_.size();
        for (int i = 0; i < size; i++) {
            if (elementName.equals(stack_.get(i)))
                level++;
        }
        return level;
    }


    public void parseHelp(String localName) throws Exception {
        try {
            if (localName.equals("text")) {
                help_.helpInfo_ = buf_.toString().trim();
            } else if (localName.equals("catalog")) {
                // vector_.addElement(atts_.getValue(0));
                // vector_.addElement(buf_.toString().trim());
            }
        } catch (Exception ex) {
            throw new Exception(activity_.getString(R.string.prasedatafail));
        }
    }


    // 解析九宫格报文
    void parseLoginResult(String localName) throws Exception {
        try {
            if (localName.equalsIgnoreCase("phone_identity")) {
                if (eventType_ == START_TAG) {
                	um_.loginStatus_ = getAttrString("loginstatus"); // 登录状态
                    um_.name_ = getAttrString("name"); // 用户名
                    um_.versionNum_ = getAttrString("version"); // 版本
                    um_.loginTimes_ = getAttrString("loginTimes"); // 登录时间
                    um_.lastLogin_ = getAttrString("lastLogin"); // 上次登录时间
                    um_.checkInfo_ = getAttrString("checkInfo"); // 预留信息
                    um_.apk_host_path = getAttrString("apkPath");//服务器APK路径
                    um_.menuV_ = new Vector<String>();
                    tempChannel_ = null;
                    String loginUrl = getAttrString("loginUrl");
                    if (loginUrl != null) {
                    	//存储登录地址
                    	BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.LOGIN_URL, loginUrl);
                    }
                } 
            } else if (localName.equalsIgnoreCase("announcements")) { // 信息公告
				if (eventType_ == START_TAG) {
					String totaltemp=getAttrString("total"); // 总数
					String validtemp=getAttrString("valid"); // 有效数
					int total = Integer.parseInt(totaltemp);
					int valid = Integer.parseInt(validtemp);
					tempChannel_.total_=total;
					int localTotal=0;
					if(Mid.saveProperty_.get(tempChannel_.id())!=null){
						localTotal = Integer.parseInt(Mid.saveProperty_.get(tempChannel_.id()).toString());
					}
					int show = (total - localTotal) <= valid ? (total - localTotal): valid;
					tempChannel_.setShowNew(show);
				}
			} else if (localName.equalsIgnoreCase("channel")) { // 频道节点
				if (eventType_ == START_TAG) {
					tempChannel_ = new Channel(repo_);
					tempChannel_.isCollection_ = true;
				} else {
					repo_.addChannel(tempChannel_);
				}
            } else if (localName.equalsIgnoreCase("id")) { // 频道id
                if (eventType_ == END_TAG) {
                    tempChannel_.setId(buf_.toString().trim());
                }
            } else if (localName.equalsIgnoreCase("title")) { // 频道标题
                if (eventType_ == END_TAG) {
                    tempChannel_.setTitle(buf_.toString().trim());
                }
            } else if (localName.equalsIgnoreCase("shortcut")) { // 快捷方式
                if (eventType_ == END_TAG) {
                    tempChannel_.shortCut_ = buf_.toString().trim();
                    um_.menuV_.addElement(tempChannel_.shortCut_);
                }
            } else if (localName.equalsIgnoreCase("type")) {
                if (eventType_ == END_TAG) {
                    tempChannel_.setFeedType(buf_.toString().trim());
                }
            } else if (localName.equalsIgnoreCase("downloadCode")) {
                if (eventType_ == END_TAG) {
                    um_.downloadCode_ = buf_.toString().trim();
                }
            }
        } catch (Exception ex) {
            throw new Exception(activity_.getString(R.string.prasedatafail));
        }
    }

	/**
     * Given an Atom file describing POIs in a channel, store them in memory. We need to handle POI definitions and
     * entry properties for RPC calls.
     * 
     * @param xml
     *            POI description downloaded from server.
     * @param poiList
     *            Returns parsed POI objects in this Vector.
     * @param channel
     *            Channel to which POIs belong.
     * @throws java.lang.Exception
     *             May throw parsing error.
     */
    public void parsePOI(String localName) throws Exception {
        try {

            if (eventType_ == START_TAG) {
                if (localName.equalsIgnoreCase("entry")) {
                    poi_ = new POI();
                }

                // 如果父结点名是“entry”则执行相关操作
                if (stack_.indexOf("entry") != -1) {
                    // 表示正处于entry节点??�套�?
                    readOnePoi(localName);

                } else if (stack_.indexOf("property") != -1) {
                    readChannelProperties(localName);
                }
            } else {
                String text = "";
                if (null != buf_)
                    text = buf_.toString().trim();
                // 匹配节点处理方法
                if (localName.equalsIgnoreCase("entry")) {
                    poiList_.addElement(poi_);
                } else if (localName.equalsIgnoreCase("current_page")) {
                    channel_.paging_.setCurrentPage(Integer.parseInt(text));
                } else if (localName.equalsIgnoreCase("last_page")) {
                    channel_.paging_.setLastPage(Integer.parseInt(text));
                }
                // 匹配层级节点处理方法
                if (stack_.indexOf("entry") != -1) {
                    // 表示正处于entry节点嵌套�?
                    readOnePoi(localName);
                } else if (stack_.indexOf("property") != -1) {
                    // 处于节点property嵌套�?
                    readChannelProperties(localName);
                }

            }
        } catch (Exception ex) {
            throw new Exception(activity_.getString(R.string.prasedatafail));
        }
    }

    // return the poi from the xml.
    private void parseOnePOI(String localName) throws Exception {
        try {
            readOnePoi(localName);
        } catch (Exception ex) {
            throw new Exception(activity_.getString(R.string.prasedatafail));
        }
    }

    /**
     * Read channel properties.
     */
    private void readChannelProperties(String localName) throws IOException {
        if (eventType_ == START_TAG) {
            if (localName.equalsIgnoreCase("mappin")) {
                String term = getAttrString("term");
                String type = getAttrString("type");
                String url = getAttrString("href");
                String hot = getAttrString("hotspot");
                PoiRepository.addMapPin(term, type, url, hot);
            }
        }
    }

    private ChannelParam readOneChannelParam(String localName) {
        label_ = getAttrString("label");
        name_ = getAttrString("name");
        value_ = getAttrString("value");
        type_ = getAttrString("type");
        placeholder_ = getAttrString("placeholder");
        selectSort_ = getAttrString("sort");
        sortKey_ = getAttrString("sortkey");
        fillType_ = getAttrString("fillType");
        isChecked_ = false;
        if (null != getAttrString("checked"))
            isChecked_ = true;
        Utils.printOutToConsole("got params " + name_ + " " + value_ + " " + label_ + " " + type_ + " " + fillType_);
        p_ = new ChannelParam(name_, label_, value_, placeholder_, type_, fillType_, selectSort_, sortKey_);
        p_.isChecked_ = isChecked_;
        return p_;
    }

    /**
     * Parse definitions of a single POI (an entry in an Atom feed).
     */
    private POI readOnePoi(String localName) throws Exception {
        if (eventType_ == START_TAG) {
            if (localName.equalsIgnoreCase("link")) {
                String url = getAttrString("href");
                String rel = getAttrString("rel");
                String len = getAttrString("length");
                if (url != null && rel != null) {
                    if (rel.equals("self")) {
                        poi_.url_ = url.trim();
                    } else if (rel.equals("content")) {
                        poi_.showEntryUrl_ = url;
                        if (len != null)
                            poi_.showEntryLen_ = Integer.parseInt(len);
                    }
                }
            }
            if (stack_.indexOf("property") != -1) {
                readOnePoiProperty(localName);
            }
        } else {
            String text = "";
            if (null != buf_)
                text = buf_.toString().trim();
            if (localName.equals("title")) {
                poi_.setName(text);
                // XXX FIXME: this is a HACK! We should have a separate field for tags.
                poi_.tag_ = text;
            } else if (localName.equals("updated")) {
                poi_.setUpdated(text);
            } else if (localName.equals("id")) {
                Utils.printOutToConsole("id=" + text);
                if (text.startsWith("urn"))
                    poi_.id_ = 0;
                else {
                    try {
                        poi_.id_ = Integer.parseInt(text);
                    } catch (Exception ignored) {
                        poi_.id_ = 0;
                    }
                }
            } else if (localName.equals("content")) {
                poi_.desc_ = text;
            } else if (localName.equals("description")) {
                poi_.desc_ = text;
            }
            if (stack_.indexOf("property") != -1) {
                readOnePoiProperty(localName);
            }
        }
        return poi_;

    }

    private void readOnePoiProperty(String localName) throws Exception {
        // We have to do these before calling nextText() because we need their attributes
        if (eventType_ == START_TAG) {
            if (localName.equals("ev")) {
                p_ = readOneChannelParam(localName);
            } else if (localName.equalsIgnoreCase("eattr")) {
                String aName = getAttrString("name");
                String aValue = getAttrString("value");
                if (aName != null && aValue != null) {
                    poi_.addExtAttr(aName, aValue);
                }
            } else if (localName.equalsIgnoreCase("ad")) {
                poi_.adUrl_ = getAttrString("href");
            } else if (localName.equalsIgnoreCase("img")) {
                poi_.totalImages_++;
                String url = getAttrString("src");
                if (url.equals("ewp_app_logo")) {
                	Utils.hiddenTitleBar_ = true;
                }
                poi_.imgUrls_.addElement(url);
                String link = getAttrString("href");
                poi_.imgLinks_.addElement(link);
                if (link == null) {
                    poi_.imgLinks_.addElement(link);
                }
            }
        } else {
            String text = "";
            if (null != buf_)
                text = buf_.toString().trim();
            if (localName.equals("ev")) {
                // Channel
                poi_.entryVariables_.addElement(p_);
            } else if (localName.equals("phone")) {
                poi_.phone_ = text;
            } else if (localName.equals("occurrence")) {
                poi_.addOccurrence(text);
            }
        }
    }


    String getError(byte[] str) {
        try {
            return getAppError(new String(str, "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            Utils.printOutToConsole("AtomParser-getError:" + ex.toString());
            return null;
        }
    }

    /**
     * Retrieve error string.
     */
    String getAppError(String str) {
        if (str == null)
            return null;
        if (str.startsWith("<error")) {
            int idx = str.indexOf("string=\"");
            if (idx == -1)
                return null;
            idx += 8;
            int idx2 = str.indexOf('\"', idx);
            if (idx != -1 && idx2 > idx) {
                return str.substring(idx, idx2);
            } else {
                return null;
            }
        } else if (str.startsWith("#") || str.startsWith("<html")) {
            // This was caused by a Rails server error and we get a HTML error message.
            return activity_.getString(R.string.noconnect);
        } else {
            return null;
        }
    }


    private void parsekXMLItems(String localName) throws Exception {
        int taglength = localName.length();
        if (eventType_ == START_TAG) {
            parsekXMLItemsStart(localName, taglength);
        } else {
            parsekXMLItemsEnd(localName, taglength);
        }

        // Adjust fonts
        htmlItem_.ls_.font_ = new Paint();
        htmlItem_.ls_.fontStyle_ = Typeface.NORMAL;
        if (htmlItem_.ls_.isBold_ && htmlItem_.ls_.isItalic_) {
            htmlItem_.ls_.fontStyle_ = Typeface.BOLD_ITALIC;
        }
        if (htmlItem_.ls_.isBold_) {
            htmlItem_.ls_.fontStyle_ = Typeface.BOLD;
        }
        if (htmlItem_.ls_.isItalic_) {
            htmlItem_.ls_.fontStyle_ = Typeface.ITALIC;
        }
        if (htmlItem_.ls_.isLink_) {
            htmlItem_.ls_.font_.setUnderlineText(true);
        }
        htmlItem_.ls_.font_.setTextSize(htmlItem_.ls_.fontSize_);
        htmlItem_.ls_.font_.setTypeface(Typeface.defaultFromStyle(htmlItem_.ls_.fontStyle_));
    }

    private void parsekXMLItemsStart(String localName, int taglength) throws Exception {
        if (skipDiv) {
            htmlItem_.textInForm_ = null;
            return;
        }
        String accessory = getAttrString("accessory");
        if (accessory != null) {
            htmlItem_.ls_.isLink_ = true;
            htmlItem_.ls_.linkTarget_ = accessory;
        }
        String classStr = getAttrString("class");
        try {
            htmlItem_.pushStyle(localName, classStr);
        } catch (Exception e) {
            Utils.printException(e);
        }
        // MODIFY to call SUBROUTINE for each tag, which creates an HTMLITEM, frobs layout state.
        if(localName.equalsIgnoreCase("titlebar")){
        	titleBarTitle_ = getAttrString("title");
        	rightButton_ = getAttrString("rightbutton");
        	leftButton_ = getAttrString("leftbutton");
        } else if (localName.equalsIgnoreCase("BR")) {
            htmlItem_.addLsItem(activity_); // add a new item means will start at a new line.
        } else if (localName.equalsIgnoreCase("P")) {
            PTag_ = true;
            htmlItem_.addLsItem(activity_);
            htmlItem_.view_ = new Wrap();
            htmlItem_.addLsItem(activity_);
        } else if (localName.equalsIgnoreCase("STRONG") || localName.equalsIgnoreCase("B")) {
            htmlItem_.ls_.isBold_ = true;
        } else if (localName.equalsIgnoreCase("A")) {
            // hyperlink
            htmlItem_.addLsItem(activity_);
            // Look for the HREF target value.
            htmlItem_.ls_.isLink_ = true;
            htmlItem_.ls_.linkTarget_ = getAttrString("href");
        } else if (((localName.charAt(0) == 'h') || (localName.charAt(0) == 'H')) && (taglength == 2) && ("123456".indexOf(localName.charAt(1)) != -1)) { // <h1> - <h6>
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.isBold_ = true;
            if ("56".indexOf(localName.charAt(1)) != -1)
                htmlItem_.ls_.fontSize_ = ConfigManager.SIZE_SMALL;
            else if ("34".indexOf(localName.charAt(1)) != -1)
                htmlItem_.ls_.fontSize_ = ConfigManager.SIZE_MEDIUM;
            else
                htmlItem_.ls_.fontSize_ = ConfigManager.SIZE_LARGE;
        } else if (localName.equalsIgnoreCase("DIV")) {
            id_ = getAttrString("id");
            style_ = getAttrString("style");
            cla_ = getAttrString("class");
            name = getAttrString("name");
            if (mid_.cacheDivs != null) {
                PoiSelection poisel = mid_.getCurrentPoiSelection(false, activity_);
                String channelID = poisel.channel_.id();
                if (mid_.cacheDivs.get(getAttrString("name")) != null && poisel.poiRepo_.getActionSize() == 0 && channelID.equals("16")) {
                    Utils.printOutToConsole("*****************找到了缓存的DIV:" + getAttrString("name") + "***************");
                    skipDiv = true;
                    return;
                }
            }
            String strHeight = getAttrString("height");
            if (id_ != null && cla_ != null && id_.equals("ewp_back")) {
                if (cla_.equals("no")) {
                    activity_.blackView_ = 1;
                } else if (cla_.equals("clear")) {
                    activity_.blackView_ = 2;
                    mid_.poiRepo_.doClearActionPoi();// clear stack.
                } else if (cla_.equals("refresh")) {
                    activity_.blackView_ = 3;
                 // 重新刷新一下该channel的第一个界面
                    mid_.poiRepo_.doRefreshActionPOi();
                } else {
                    activity_.blackView_ = 0;
                }
            }
            if ((id_ != null && style_ != null && style_.equals("hidden"))) {
                htmlItem_.ls_.id_ = null;
                htmlItem_.ls_.isHidden_ = true;
            } else {
                htmlItem_.addLsItem(activity_);
                Div tempLL = new Div(activity_);
                tempLL.setOrientation(LinearLayout.VERTICAL);
                tempLL.name_ = name;
                tempLL.setTag(name);
                tempLL.strHeight_ = strHeight;
                if (stack_.contains("form")) {
                    // 由于Form控件涉及到联动，但android界面等级有限，现在有一部分控件在xml中是属于form的内层结构，
                    // 但是却没有被添加到form管理器中。所以通过这种方法来矫正未放到form管理器中的控件联动
                    tempLL.setForm(htmlItem_.formLayout_);
                }
                Div ll = null;
                ll = htmlItem_.peekDiv();
                if (ll != null) {
                    ll.addChild(tempLL);
                }
                htmlItem_.pushDiv(tempLL);
                // 将div添加到联动控件队列中
                activity_.vWidgetArray_.add(tempLL);
            }
            if (id_ != null && cla_ != null && id_.equalsIgnoreCase("pushState") && poi_ != null) {
            	if (cla_.equalsIgnoreCase("skip")) {
            		poi_.skip_ = true;
            	} else if (cla_.equalsIgnoreCase("skip1")){
            		poi_.skip_1 = true;
            	} else if (cla_.equalsIgnoreCase("pop")) {
            		poi_.popStack_ = true;
            	} else if (cla_.contains("skip_number_")) {
            		poi_.skip_2 = true;
            		poi_.skip_number = cla_;
            	}
            }
            String updateTable = getAttrString("updateTable");
            if (null != updateTable && updateTable.equals("true")) {
            	BaseView.updateTable_ = true;
            }
        } else if (localName.equalsIgnoreCase("UL")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.olNum_ = 0;
        } else if (localName.equalsIgnoreCase("OL")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.olNum_ = 1;
        } else if (localName.equalsIgnoreCase("LI")) {
            htmlItem_.addLsItem(activity_);
            if (htmlItem_.ls_.olNum_ == 0)
                htmlItem_.ls_.tag_ = "  - ";// UL
            else {
                htmlItem_.ls_.tag_ = "  " + (htmlItem_.ls_.olNum_++) + ". ";// OL
                htmlItem_.ls_.isFirstTag_ = true;
            }
        } else if (localName.equalsIgnoreCase("TABLE")) {
            htmlItem_.addLsItem(activity_);
            String hasborder = getAttrString("border");
            htmlItem_.table_ = new Table(activity_);
            htmlItem_.table_.attrName_ = getAttrString("name");
            htmlItem_.table_.form = getAttrString("form");
            if (null != getAttrString("full") && getAttrString("full").equalsIgnoreCase("width")){
				htmlItem_.table_.isfull_ = true;
			}
            htmlItem_.table_.updateUrl_ = getAttrString("url");
            htmlItem_.table_.updateTime_ = getAttrString("update");
            htmlItem_.table_.textColor_ = htmlItem_.ls_.color_;
            htmlItem_.table_.setTag(getAttrString("name"));
            if (hasborder != null && Integer.parseInt(hasborder) > 0) {
                htmlItem_.table_.hasBorder_ = true;
            } else {
                htmlItem_.table_.hasBorder_ = false;
            }
            if (stack_.contains("form")) {
                // 由于Form控件涉及到联动，但android界面等级有限，现在有一部分控件在xml中是属于form的内层结构，
            	 // 但是却没有被添加到form管理器中。所以通过这种方法来矫正未放到form管理器中的控件联动
                htmlItem_.table_.setForm(htmlItem_.formLayout_);
            }
        } else if (localName.equalsIgnoreCase("TR")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.isTable_ = true;
            htmlItem_.currentCol_ = -1;
            htmlItem_.currentRow_++;
            String addendum = getAttrString("addendum");
            htmlItem_.table_.addendum_.add(addendum);
            htmlItem_.table_.accessory_.add(accessory);
        } else if (localName.equalsIgnoreCase("TD")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.currentCell_ = new Table.Cell();
            htmlItem_.table_.addCell(htmlItem_.currentCell_);
            parseSpan(htmlItem_.table_);
        } else if (localName.equalsIgnoreCase("TH")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.isBold_ = true;
            htmlItem_.currentCell_ = new Table.Cell();
            htmlItem_.table_.addCell(htmlItem_.currentCell_);
            parseSpan(htmlItem_.table_);
        } else if (localName.equalsIgnoreCase("HR")) {
            htmlItem_.addLsItem(activity_);
            parserCSSInLine(localName, htmlItem_.ls_, eventType_);
            htmlItem_.createNewItem(activity_, underscores_.toString(), false);
        } else if (localName.equalsIgnoreCase("DD")) {
            htmlItem_.ls_.tag_ = "    ";
        } else if (localName.equalsIgnoreCase("FONT")) {
            String colorVal = getAttrString("color");
            htmlItem_.ls_.prevColor = htmlItem_.ls_.color_;
            htmlItem_.ls_.color_ = Utils.getColorFromString(colorVal);
        } else if (localName.equalsIgnoreCase("IMG")) {
            String src = getAttrString("src");
            String url = getAttrString("url");
        	htmlItem_.addLsItem(activity_);
            if (src.equals("ewp_app_logo")) {
            	Utils.hiddenTitleBar_ = true;
            }
            String align = getAttrString("align");
            String alt = (activity_.getString(R.string.loading));
			boolean isload = true;
            htmlItem_.layoutImageElement((stack_.indexOf("form") != -1), src, url, align, alt, activity_, isload);
        } else if (localName.equalsIgnoreCase("BASE")) {
            htmlItem_.addLsItem(activity_);
            String href = getAttrString("href");
            if ((href != null) && !(href.equals(""))) {
                htmlItem_.ls_.isLink_ = true;
                htmlItem_.ls_.linkTarget_ = href;
            }
        } else if (localName.equalsIgnoreCase("I") || localName.equalsIgnoreCase("EM")) {
            htmlItem_.ls_.isItalic_ = true;
        } else if (localName.equalsIgnoreCase("FORM")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.formLayout_ = new FormLayout(activity_);
            htmlItem_.formLayout_.attrName_ = getAttrString("name");
            htmlItem_.formLayout_.setTag(htmlItem_.formLayout_.attrName_);
            htmlItem_.ls_.isForm_ = true;
            htmlItem_.ls_.faction_ = new FormAction(mid_, activity_);
            String actionUrl = getAttrString("action");
            htmlItem_.ls_.actionUrl_ = actionUrl;
            htmlItem_.hidden_ = null;
            htmlItem_.ls_.faction_.action_ = actionUrl;
            if (htmlItem_.ls_.id_ != null)
                htmlItem_.ls_.faction_.name_ = htmlItem_.ls_.id_;
            else
                htmlItem_.ls_.faction_.name_ = getAttrString("name");
            htmlItem_.ls_.faction_.isHidden_ = htmlItem_.ls_.isHidden_;
        } else if (localName.equalsIgnoreCase("input")) {
            htmlItem_.addLsItem(activity_);
            addToForm(localName, activity_, htmlItem_);
        } else if (localName.equalsIgnoreCase("textarea")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.view_ = new Wrap();
            htmlItem_.addLsItem(activity_);
            final String name = getAttrString("name");
            final String value = getAttrString("value");
            final String style = getAttrString("style");
            int maxL = 1024;
            try{
            	maxL = Integer.parseInt(getAttrString("maxleng"));
            } catch (Exception e) {
            }
            final int maxLeng = maxL;
            activity_.runOnUiThread(new Runnable() {
                public void run() {
                    mTextField txtField = new mTextField(activity_, null, value, maxLeng, ConfigManager.InputType_CLASS_TEXT, Component.MAX_WIDTH, -1);
                    if (style != null && style.indexOf("-wap-input-required") != -1) {
                        if (style.indexOf("'true'") != -1) {
                            txtField.required_ = true;
                        }
                    }
                    txtField.setPadding(5, 0, 30, 0);                 	
                    txtField.attrName_ = name;
                    txtField.setTag(name);
                    txtField.attrValue_ = value;
                    htmlItem_.view_ = txtField;
                }
            });
            synchronized (this) {
                while (htmlItem_.view_ == null || !(htmlItem_.view_ instanceof mTextField)) {
                    wait(100);
                }
            }
            htmlItem_.addLsItem(activity_);
        } else if (stack_.indexOf("select") != -1) {
            // 表示处于“select”节点中
            if (localName.equalsIgnoreCase("select")) {
                htmlItem_.addLsItem(activity_);
                selectSort_ = getAttrString("sort");
                selectUrl_ = getAttrString("url");
                selectIcon_ = getAttrString("icon"); 
                selectForm = getAttrString("form");
                selectName_ = getAttrString("name");
                String saveTemp = getAttrString("save");
                String trueSaveTemp = getAttrString("trueSave");
                if (null != saveTemp && saveTemp.contains("yes")) {
                    selectSave_ = true;
                } else {
                    selectSave_ = false;
                }
                if (null != trueSaveTemp && trueSaveTemp.contains("yes")) {
                	selectTrueSave_ = true;
                } else {
                	selectTrueSave_ = false;
                }
                if (htmlItem_.ls_.isForm_) {
                    accessory_ = getAttrString("accessory");
                    name_ = getAttrString("name");
                    rname_ = getAttrString("rename");
                    String multiple = getAttrString("multiple");
                    if (multiple != null) {
                        selectToCheckbox(localName, htmlItem_, name_);
                    } else {
                        // 初始化或者清空下拉框中的Option集合
                        if (null == options_) {
                            options_ = new Vector<Option>();
                        } else {
                            options_.clear();
                        }
                    }
                }
            } else if (localName.equalsIgnoreCase("option")) {
            	 // 节点名为”option"
                sortKey_ = getAttrString("sortkey");
                value_ = getAttrString("value");
                select_ = getAttrString("selected");
                group_ = getAttrString("group");
                ref_ = getAttrString("ref");
                relaEnable_ = Utils.string2Array(getAttrString("enable"), ",");
                relaDisable_ = Utils.string2Array(getAttrString("disable"), ",");
                relaVisible_ = Utils.string2Array(getAttrString("visible"), ",");
                relaInvisible_ = Utils.string2Array(getAttrString("invisible"), ",");
            }
		} else if (localName.equalsIgnoreCase("label")) {
			htmlItem_.addLsItem(activity_);
			name_ = getAttrString("name");
			value_ = getAttrString("value");
		} else if (localName.equalsIgnoreCase("ratingbar")) {
			htmlItem_.addLsItem(activity_);
			name_ = getAttrString("name");
			value_ = getAttrString("value");
		} else if (localName.equalsIgnoreCase("viewflipper")) {
			htmlItem_.addLsItem(activity_);
			activity_.runOnUiThread(new Runnable() {
				public void run() {
					mViewFlipper viewFlipper = new mViewFlipper(activity_);
					htmlItem_.view_ = viewFlipper;
				}
			});
			synchronized (this) {
				while (htmlItem_.view_ == null || !(htmlItem_.view_ instanceof mViewFlipper)) {
					wait(100);
				}
			}
			mViewFlipper temp = (mViewFlipper) htmlItem_.view_;
			String srcs = URLDecoder.decode(getAttrString("src")); // 图片的地址
			String urls = getAttrString("url"); // 点击图片的链接
			int covers = 0; // 封面数

			if ((null != srcs) && (null != urls)) {
				ArrayList<ImageItem> items_ = new ArrayList<ImageItem>();
				String[] imgSrcs = srcs.split(";");
				String[] imgUrls = urls.split(";");

				covers = Math.min(imgSrcs.length, imgUrls.length);
				mViewFlipper.gridcount = covers;
				if (covers > 0) {
					ImageItem tempItem_ = null;
					String alt = (activity_.getString(R.string.loading));
					Bitmap image = Utils.createImgWaitLoad(mid_, alt, 0x88888888, Utils.screenWidth_ / mViewFlipper.eachCount, Utils.getSystemScaledValue(180));
					for (int i = 0; i < covers; i++) {
						// Build the new image item.
						tempItem_ = new ImageItem(activity_, image);
						tempItem_.setLayoutParams(new LinearLayout.LayoutParams(Utils.screenWidth_ / mViewFlipper.eachCount, Utils.getSystemScaledValue(180)));

						tempItem_.setUrl(imgUrls[i]);
						// make an absolute SRC URL to get the image
						String url = imgSrcs[i];
						if (htmlItem_.imageRemote_ == null)
							htmlItem_.imageRemote_ = new Vector<Bitmap>();
						if (htmlItem_.imageUrlRemote_ == null)
							htmlItem_.imageUrlRemote_ = new Vector<String>();
						// add this image link in the list of image url.
						htmlItem_.imageUrlRemote_.addElement(url);

						if (htmlItem_.itemRemote_ == null)
							htmlItem_.itemRemote_ = new Vector<ImageView>();
						htmlItem_.itemRemote_.addElement(tempItem_);
						items_.add(tempItem_);
					}
					if (null != items_ && items_.size() >= 0) {
						temp.imageItems = items_;
					}
				} else {
					mViewFlipper.gridcount = 0;
				}
			}
			temp.initView();

			try {
				htmlItem_.addLsItem(activity_);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (localName.equalsIgnoreCase("waterfall")) {
			htmlItem_.addLsItem(activity_);
			name_ = getAttrString("name");
			value_ = getAttrString("value");

			activity_.runOnUiThread(new Runnable() {
				public void run() {
					String json = getAttrString("json");
					Waterfall waterfall = new Waterfall (activity_,name_,json);
					waterfall.setNextUrl_(getAttrString("nextUrl"));
					waterfall.setDetailUrl_(getAttrString("itemUrl"));
					String infoType = getAttrString("infoType");
					waterfall.setInfoType_(infoType);
					if (null != infoType) {
						if (infoType.equals("2")) {
							// 在餐馆列表页面清空购物车缓存
							ShopCart.order.clear();
							htmlItem_.view_ = waterfall;
						} else if (infoType.equals("3")) {
							ShopCart shopCart = new ShopCart(activity_, waterfall);
							htmlItem_.view_ = shopCart;
						} else {
							htmlItem_.view_ = waterfall;
						}
					} else {
						htmlItem_.view_ = waterfall;
					}
				}
			});
			synchronized (this) {
				while (htmlItem_.view_ == null || !(htmlItem_.view_ instanceof Waterfall || htmlItem_.view_ instanceof ShopCart)) {
					wait(100);
				}
			}
            htmlItem_.addLsItem(activity_);
		} else if (localName.equalsIgnoreCase("uploadfile")) { // 相片上传
			htmlItem_.addLsItem(activity_);
			name_ = getAttrString("name");
			value_ = getAttrString("value");
			UploadFile temp = new UploadFile(activity_, name_, value_);
			htmlItem_.view_ = temp;
            htmlItem_.addLsItem(activity_);
		} else if (localName.equalsIgnoreCase("shopcartlist")) { // 本地购物清单
			htmlItem_.addLsItem(activity_);
			name_ = getAttrString("name");
			activity_.runOnUiThread(new Runnable() {
				public void run() {
					ShopCartList temp = new ShopCartList(activity_, name_);
					htmlItem_.view_ = temp;
				}
			});
			synchronized (this) {
				while (htmlItem_.view_ == null || !(htmlItem_.view_ instanceof ShopCartList || htmlItem_.view_ instanceof ShopCartList)) {
					wait(100);
				}
			}
            htmlItem_.addLsItem(activity_);
		} else if (localName.equalsIgnoreCase("combobox")) {
			htmlItem_.addLsItem(activity_);
			name_ = getAttrString("name");
			value_ = getAttrString("value");
			String subText = getAttrString("subText");
			String subUrl = getAttrString("subUrl");
			ComboBox combobox = new ComboBox(activity_, 1, value_, subText, subUrl);
			combobox.setRelationName(getAttrString("relation"));
			htmlItem_.view_ = combobox;
			
		}
		
    }

    private void parsekXMLItemsEnd(String localName, int taglength) throws Exception {
        if (skipDiv && !localName.equalsIgnoreCase("DIV")) {
            htmlItem_.textInForm_ = null;
            return;
        }

        String text = "";
        if (null != buf_)
            text = Utils.insteadOfSpecillCharacter(buf_.toString().trim(), false);

        // 节点换行的方法
        if (localName.equalsIgnoreCase("BR")) {
            htmlItem_.textInForm_ = null;
            htmlItem_.view_ = new Wrap();
            htmlItem_.addLsItem(activity_); // add a new item means will start at a new line.
        } else if (localName.equalsIgnoreCase("P")) {
            PTag_ = false;
            htmlItem_.addLsItem(activity_);
            htmlItem_.view_ = new Wrap();
            htmlItem_.addLsItem(activity_);
        } else if (localName.equalsIgnoreCase("STRONG") || localName.equalsIgnoreCase("B")) {
            htmlItem_.ls_.isBold_ = false;
        } else if (localName.equalsIgnoreCase("A")) {
            // hyperlink
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.isLink_ = false;
            htmlItem_.ls_.linkTarget_ = null;
        } else if (((localName.charAt(0) == 'h') || (localName.charAt(0) == 'H')) && (taglength == 2) && ("123456".indexOf(localName.charAt(1)) != -1)) { // <h1> - <h6>
            htmlItem_.ls_.isBold_ = false;
            htmlItem_.ls_.fontSize_ = ConfigManager.SIZE_MEDIUM;
            Label itemLabel = new Label(activity_, text, false, false, false);
            itemLabel.attrName_ = name_;
            itemLabel.attrValue_ = value_;
            itemLabel.setTag(name_);
            if (stack_.contains("form")) {
                // 由于Form控件涉及到联动，但android界面等级有限，现在有一部分控件在xml中是属于form的内层结构，
                // 但是却没有被添加到form管理器中。所以通过这种方法来矫正未放到form管理器中的控件联动
                itemLabel.setForm(htmlItem_.formLayout_);
            }
            htmlItem_.view_ = itemLabel;
            htmlItem_.textInForm_ = null;
            htmlItem_.addLsItem(activity_);
        } else if (localName.equalsIgnoreCase("DIV")) {
            if (skipDiv) {
                activity_.invisibleViews_ = null;
                if (activity_.invisibleViews_ == null) {
                    activity_.invisibleViews_ = new HashMap<String, ArrayList<Component>>();
                }
                activity_.invisibleStyles_ = null;
                if (activity_.invisibleStyles_ == null) {
                    activity_.invisibleStyles_ = new HashMap<String, CssStyle>();
                }
                activity_.invisibleViews_.put(name, mid_.cacheDivs.get(name));
                activity_.invisibleStyles_.put(name, mid_.cacheDivStyles_.get(name));
                skipDiv = false;
                return;
            }

            if ((id_ != null && style_ != null && style_.equals("hidden")) || htmlItem_.ls_.isHidden_) {
                htmlItem_.ls_.id_ = null;
                htmlItem_.ls_.isHidden_ = false;
            } else {
                // add the text in <DIV>.
                htmlItem_.addLsItem(activity_);

                Div currentDiv = null;
                // pop the current ViewGroup.
                currentDiv = htmlItem_.popDiv();
                ParseHtml.applyCssOnComponent(currentDiv, htmlItem_.peekStyle(), htmlItem_.nodeStyles_);

                htmlItem_.addNewDiv(currentDiv);

                // htmlItem.ls_.alignment_ = Graphics.BOTTOM;
                htmlItem_.ls_.color_ = htmlItem_.ls_.prevColor;
            }
        } else if (localName.equalsIgnoreCase("UL")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.olNum_ = -1;
        } else if (localName.equalsIgnoreCase("OL")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.olNum_ = -1;
        } else if (localName.equalsIgnoreCase("LI")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.tag_ = null;
            htmlItem_.ls_.isFirstTag_ = false;
        } else if (localName.equalsIgnoreCase("TABLE")) {
            htmlItem_.addLsItem(activity_);
            ParseHtml.applyCssOnComponent(htmlItem_.table_, htmlItem_.peekStyle(), htmlItem_.nodeStyles_);
            htmlItem_.view_ = htmlItem_.table_;
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.isTable_ = false;
            htmlItem_.table_ = null;
            htmlItem_.currentRow_ = -1;
            htmlItem_.currentCol_ = -1;
        } else if (localName.equalsIgnoreCase("TR")) {
            htmlItem_.table_.addRowStyle(htmlItem_.peekStyle());
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.isTable_ = false;
        } else if (localName.equalsIgnoreCase("TD")) {
            htmlItem_.addLsItem(activity_);
            ParseHtml.applyCssOnComponent(htmlItem_.currentCell_, htmlItem_.peekStyle(), htmlItem_.nodeStyles_);
            htmlItem_.currentCell_.mould();
        } else if (localName.equalsIgnoreCase("TH")) {
            htmlItem_.addLsItem(activity_);
            ParseHtml.applyCssOnComponent(htmlItem_.currentCell_, htmlItem_.peekStyle(), htmlItem_.nodeStyles_);
            htmlItem_.currentCell_.mould();
            htmlItem_.ls_.isBold_ = false;
        } else if (localName.equalsIgnoreCase("HR")) {
            htmlItem_.addLsItem(activity_);
        } else if (localName.equalsIgnoreCase("DD")) {
            htmlItem_.ls_.tag_ = null;
        } else if (localName.equalsIgnoreCase("FONT")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.ls_.color_ = htmlItem_.ls_.prevColor;
        } else if (localName.equalsIgnoreCase("I") || localName.equalsIgnoreCase("EM")) {
            htmlItem_.ls_.isItalic_ = false;
        } else if (localName.equalsIgnoreCase("FORM")) {
            htmlItem_.addLsItem(activity_);
            // 赋空form节点，表示已处于form节点�?

            htmlItem_.ls_.isForm_ = false;
            htmlItem_.view_ = htmlItem_.formLayout_;
            htmlItem_.addLsItem(activity_);
            htmlItem_.formLayout_ = null;
            htmlItem_.ls_.actionUrl_ = null;
            htmlItem_.textInForm_ = null;
            if (htmlItem_.ls_.faction_ != null) {
                htmlItem_.ls_.faction_.hidden_ = htmlItem_.hidden_;
                activity_.addForm(htmlItem_.ls_.faction_);
            }
        } else if (localName.equalsIgnoreCase("input")) {
            appendInputComponent(localName);
            htmlItem_.textInForm_ = null;
        } else if (localName.equalsIgnoreCase("scrollview")) {
        	htmlItem_.addLsItem(activity_);
        } else if (localName.equalsIgnoreCase("club")) {
        	htmlItem_.addLsItem(activity_);
        } else if (localName.equalsIgnoreCase("label")) {
            Label itemLabel = new Label(activity_, text, false, false, false);
            itemLabel.attrName_ = name_;
            itemLabel.attrValue_ = value_;
            itemLabel.setTag(name_);
            if (stack_.contains("form")) {
                // 由于Form控件涉及到联动，但android界面等级有限，现在有一部分控件在xml中是属于form的内层结构，
                // 但是却没有被添加到form管理器中。所以通过这种方法来矫正未放到form管理器中的控件联动
                itemLabel.setForm(htmlItem_.formLayout_);
            }
            htmlItem_.view_ = itemLabel;
            htmlItem_.textInForm_ = null;
            htmlItem_.addLsItem(activity_);
        } else if (localName.equalsIgnoreCase("textarea")) {
            htmlItem_.addLsItem(activity_);
            htmlItem_.view_ = new Wrap();
            htmlItem_.addLsItem(activity_);
        } else if (stack_.indexOf("select") != -1) {
            if (localName.equalsIgnoreCase("select")) {
                final Select temp = new Select(activity_, "");
             	if (htmlItem_.ls_.isTable_){
            		if (htmlItem_.table_.attrName_ != null){
            			temp.tableName_ = htmlItem_.table_.attrName_;
            		}
            	}
                temp.attrAccessory_ = accessory_;
                temp.attrSave_ = selectSave_;
                temp.attrTrueSave_ = selectTrueSave_;
                temp.actionUrl_ = selectUrl_;
                temp.selectIcon_ = selectIcon_;
                accessory_ = null;
                temp.attrName_ = name_;
                temp.attrRName_ = rname_;
                temp.setTag(name_);
                temp.form_ = selectForm;
                temp.selectName_ = selectName_;
                
                if (stack_.contains("form")) {
                    // 由于Form控件涉及到联动，但android界面等级有限，现在有一部分控件在xml中是属于form的内层结构，
                    // 但是却没有被添加到form管理器中。所以通过这种方法来矫正未放到form管理器中的控件联动
                    temp.setForm(htmlItem_.formLayout_);
                }
                final int size = options_.size();
                boolean hasSelect = false;
                Select.Option so = null;
                for (int i = 0; i < size; i++) {
                    so = (Select.Option) options_.elementAt(i);
                    temp.setDropdownMenuText(so);
                    // 将每个option的父系select控件保留
                    so.setParent(temp);
                    if (so.select_ != null) {
                    	// 设置默认选择项
                        temp.setCurrentMenu(temp.dropdownMenuText_.size() - 1);
                        temp.setText(so.label_);
                        hasSelect = true;
                    }
                }

                if (selectSave_||selectTrueSave_) {
                	if (null != Mid.saveProperty_ && null != htmlItem_.ls_.faction_.action_ && null != temp.attrName_) {	
                        if (temp.tableName_ != null && selectTrueSave_){
                        	so = temp.getOption((String) Mid.saveProperty_.get(htmlItem_.ls_.faction_.action_.concat(temp.tableName_).concat(temp.attrName_)));
                        } else{
                        	so = temp.getOption((String) Mid.saveProperty_.get(htmlItem_.ls_.faction_.action_.concat(temp.attrName_)));
                        }
                        if (null != so) {
                            // 如果服务端来的xml中下拉框控件里面含有save属性，且缓存中存在对应的option存储内容，则将该存储内容??�出来作为下拉框控件的显示对�?
                            String value1 = so.value_;
                            String value2 = "";
                            Select.Option optionTemp = null;
                            if ((null != temp.attrAccessory_) && (!temp.attrAccessory_.equals(""))) {
                                // 表示该下拉框控件为城市搜索类控件
                                temp.clear();
                                temp.addDropdownOption(so);
                                temp.setText(so.label_);
                            } else {
                                // 表示该下拉框控件为普通下拉框控件
                                for (int i = 0; i < size; i++) {
                                    optionTemp = (Select.Option) options_.elementAt(i);
                                    value2 = optionTemp.value_;
                                    if (value1.equals(value2)) {
                                        temp.setCurrentMenu(i);
                                        temp.setText(so.label_);
                                    }
                                }
                            }
                            hasSelect = true;
                        }
                    }
                }
                
                // temp.setOption(options_);
                if (!hasSelect && size > 0) {
                    temp.setCurrentMenu(0);
                    // 如果服务端没有传默认选择参数selected过来，则默认选择第一个
                    temp.setText(((Select.Option) temp.dropdownMenuText_.elementAt(0)).label_);
                }
                // 如果该控件在TABLE表格控件内，就适当调整输出宽高
                if (stack_.indexOf("table") != -1) {
                    temp.setLayoutParams();
                }
	            htmlItem_.view_ = temp;
	            htmlItem_.addLsItem(activity_);
                
                options_.clear();
                selectSort_ = null;
            } else if (localName.equalsIgnoreCase("option")) {
                options_.addElement(Select.initOption(activity_, text, selectSort_, sortKey_, select_, value_, group_, ref_, relaEnable_, relaDisable_, relaVisible_, relaInvisible_));
                sortKey_ = null;
                value_ = null;
                select_ = null;
                group_ = null;
                ref_ = null;
                relaEnable_ = null;
                relaDisable_ = null;
                relaVisible_ = null;
                relaInvisible_ = null;

            }
        } else if (localName.equalsIgnoreCase("style")) {
            Vector<HashMap<String, CssStyle>> vec = CssStyle.parseStyle(text);
            htmlItem_.nodeStyles_ = vec.elementAt(CssStyle.NODE);
            htmlItem_.classStyles_ = vec.elementAt(CssStyle.CLASS);
        } else if (localName.equalsIgnoreCase("ratingbar")) {
			htmlItem_.addLsItem(activity_);
			wRatingBar temp = new wRatingBar(activity_, name_, value_);
			temp.initView();
			htmlItem_.view_ = temp;
            htmlItem_.addLsItem(activity_);
		} 

        htmlItem_.ls_.isLink_ = false;
        htmlItem_.ls_.linkTarget_ = null;

        // pop the current style.
        htmlItem_.styleStack_.pop();
    }

    private void parseSpan(Table table) throws Exception {
        Table.Cell cell = htmlItem_.currentCell_;
        String cSpan = getAttrString("colspan");
        String rSpan = getAttrString("rowspan");
        if (cSpan != null)
            cell.cSpan = Integer.parseInt(cSpan);
        if (rSpan != null)
            cell.rSpan = Integer.parseInt(rSpan);
        Table.Cell preRowC = getPreRowCell(htmlItem_.currentCol_ + 1, htmlItem_.currentRow_ - 1, table);
        if ((preRowC != null) && (preRowC.r + preRowC.rSpan > htmlItem_.currentRow_)) {
            htmlItem_.currentCol_ = preRowC.c + preRowC.cSpan;
        } else {
            htmlItem_.currentCol_++;
        }
        cell.c = htmlItem_.currentCol_;
        cell.r = htmlItem_.currentRow_;
        if (cell.cSpan > 1)
            htmlItem_.currentCol_ += cell.cSpan - 1;
    }

    private Table.Cell getPreRowCell(int c, int r, Table table) throws Exception {
        if (r < 0)
            return null;
        for (int i = 0; i < table.cells_.size(); i++) {
            Table.Cell cell = (Table.Cell) table.cells_.elementAt(i);
            if (cell.c == c && cell.r == r) {
                return cell;
            }
        }
        return getPreRowCell(c, r - 1, table);
    }

    // use checkbox group to display mulitiple select.
    private void selectToCheckbox(String localName, ParseHtml htmlItem, String selectName) throws Exception {
        if (eventType_ == START_TAG) {
            if (localName.equalsIgnoreCase("option")) {
                value_ = getAttrString("value");
                select_ = getAttrString("selected");
            }
        } else if (eventType_ == END_TAG) {
            String text = "";
            if (null != buf_)
                text = buf_.toString().trim();
            if (localName.equalsIgnoreCase("option")) {
                boolean isChecked = false;
                if (select_ != null)
                    isChecked = true;
                cCheckBox temp = new cCheckBox(activity_, selectName);
                temp.setChecked(isChecked);
                temp.attrName_ = selectName;
                temp.attrValue_ = value_;
                temp.setText(text);
                htmlItem.addLsItem(activity_);
            }
        }
    }

    private void addToForm(String localName, final BaseView activity, ParseHtml htmlItem) throws Exception {
    	textFiedCount_++;
    	String type = getAttrString("type");
        String name = getAttrString("name");
        String value = getAttrString("value");
        String backValue = getAttrString("backValue");
        int styleIndex = 1;
        try {
            styleIndex = Integer.parseInt(getAttrString("styleIndex"));
        } catch (Exception e1) {
        }
        inputType_ = type;
        if (type.equals("text") || type.equals("password")) {
        	// 输入框中的提示文字，提示输入框应该输入的内容
            String hint = getAttrString("hint");
            int maxleng;
            int minleng;
            String length = getAttrString("maxleng");
            if (length != null)
                maxleng = Integer.parseInt(length);
            else
                maxleng = 1024;
            length = getAttrString("minleng");
            if (length != null)
                minleng = Integer.parseInt(length);
            else
                minleng = 0;
            if (value == null)
                value = "";

			// 输入键盘类型
			int constraints = ConfigManager.InputType_CLASS_TEXT;
			String format = getAttrString("format");
			boolean isText = true;
			if (format != null) { // format = 'phone'
				if (format.equals("n")) {
					constraints = ConfigManager.InputType_DECIMAL; // 小数
				} else if (format.equals("N")) {
					constraints = ConfigManager.InputType_NUMBER; // 整数
				} else if (format.equals("date")) {
					constraints = ConfigManager.InputType_DATETIME; // 日期
					isText = false;
				} else if (format.equals("phone")) {
					constraints = ConfigManager.InputType_PHONE; // 电话
				} else if (format.equals("digit")) {
					constraints = ConfigManager.InputType_PLUS_DIGIT; // 正整数："0-9"
				} else if (format.equals("plusNumeric")) {
					constraints = ConfigManager.InputType_PLUS_DECIMAL; // 正小数:"0-9" 和 "."
				}else if (format.equals("nochinese")) {//不能输入中文
					constraints = ConfigManager.InputType_NO_CHINESE;
				}
			}

			// 输入框必填
			boolean required = false;
			String isRequired = getAttrString("required");  // required= 'true'
			if (null != isRequired && isRequired.equals("ture")) {
				required = true;
			}
			
            if (type.equals("password")) {
                final String va = value;
                final boolean rq = required;
                final int max = maxleng;
                final int min = minleng;
                final int con = constraints;
                final String na = name;
                final String t = type;
                final String ph = hint;
                final ParseHtml hi = htmlItem;
                if (null != getAttrString("tl")) {
                	BaseView.phonenum_ = getAttrString("tl");
                }
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        mTextField c = new mTextField(activity, null, va, ph, rq, max, min, con, true);
                        setEncrypt(getAttrString("encryptMode"), c);
                        c.setTransformationMethod(new PasswordTransformationMethod());
                        c.attrName_ = na;
                        c.textFieldType_ = t;
                        c.setTag(na + textFiedCount_);
                        hi.view_ = c;
                    }
                });
                
                synchronized (this) {
                    while (htmlItem_.view_ == null || !(htmlItem_.view_ instanceof mTextField)) {
                        wait(100);
                    }
                }
            } else if (isText) {
                final String va = value;
                final boolean rq = required;
                final int max = maxleng;
                final int min = minleng;
                final int con = constraints;
                final String na = name;
                final String ph = hint;
                final ParseHtml hi = htmlItem;
                final String save = getAttrString("save");
                final String trueSave = getAttrString("trueSave");
                final String historySave = getAttrString("savehistory");
                final String mask = getAttrString("mask");
                boolean disable = true;
                String disablestr = getAttrString("disable");
                if (disablestr != null && disablestr.equalsIgnoreCase("disable")) {
                	disable = false;
                }
                final boolean enable = disable;
                final String singleChoice = getAttrString("singlechoice");
                
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                    	mTextField c = new mTextField(activity, null, va, ph, rq, max, min, con, enable);
                    	// if (null != enc)
                        // c.isEncrypt_ = true;
                      	if (htmlItem_.ls_.isTable_){
                    		if (htmlItem_.table_.attrName_ != null){
                    			c.tableName_ = htmlItem_.table_.attrName_;
                    		}
                    	}
                        setEncrypt(getAttrString("encryptMode"), c);
                        c.attrName_ = na;
                        if (trueSave != null && trueSave.equals("yes")) {
                        	c.attrTrueSave_ = true;
                        } else if (save != null && save.equals("yes")) {
                            c.attrSave_ = true;
                        }
                        
                        if (mask != null && mask.contains("true")) {
							c.mask_ = true;
						}
                        if (singleChoice != null && singleChoice.contains("true")) {
							c.isSingleChoice_ = true;
						}
                        if ((trueSave!=null&&trueSave.equals("")) ||(historySave!=null&&historySave.equals(""))) {
							c.isDeletel_ = false;
						}
                        String temp = null;
						String tempKey = null;
						String[] pn;
						// 如果控件存在此属性，则在存储中查找是否存在与之对应的内容
						if (null != c.attrName_ && null != htmlItem_ && null != htmlItem_.ls_
								&& null != htmlItem_.ls_.faction_ && null != htmlItem_.ls_.faction_.name_
								&& null != htmlItem_.ls_.faction_.action_) {
							
							if (c.tableName_ != null){
								tempKey = htmlItem_.ls_.faction_.name_.concat(htmlItem_.ls_.faction_.action_).concat(c.tableName_).concat(
										c.attrName_);
							} else {
								tempKey = htmlItem_.ls_.faction_.name_.concat(htmlItem_.ls_.faction_.action_).concat(c.attrName_);
							}
							temp = (String) Mid.saveProperty_.get(tempKey);
							if (c.attrSave_ && (null == temp || temp.equals(""))) {
								temp = (String) Mid.savePropertyTemp_.get(htmlItem_.ls_.faction_.name_ .concat(htmlItem_.ls_.faction_.action_).concat(c.attrName_));
							}
							
                            if (null != temp && !temp.equals("")) {
                            	 // 如果预支对应的内?��存在�??���??��相关的赋值操�?
                            	if (historySave != null && historySave.equalsIgnoreCase("true")) {
                            		pn = temp.split("#");
									if (c.mask_) {
										if (null != pn && pn[0].length() > 8) {
											int front = 4, last = 4;
											if (mask.length() > 4) {
												String[] an = mask.split(",");
												if ((an[1] != null || an[1].equals(""))
														&& (an[2] != null || an[2].equals(""))) {
													front = Integer.parseInt(an[1]);
													last = Integer.parseInt(an[2]);
												}
											}
											String b = pn[0].substring(0, front).concat("****")
													.concat(pn[0].substring(pn[0].length() - last));
											c.setText(b);
										} else {
											c.setText(pn[0]);
										}
										c.attrTrueValue_ = pn[0];
                            		} else {
                            		    c.setText(pn[0]);
                            		}
                            	} else {
                            		c.setText(temp);
                            	}
                            }
                        }
						
                        if (historySave != null && historySave.equalsIgnoreCase("true")) {
                        	c.saveHistory_ = true;
                        	
                        	if (temp != null) {
                        		Select sl = new Select(activity, "");
                        		sl.combobxOptionValueKey_ = tempKey;
								pn = temp.split("#");
								final int size = pn.length - 1;
								for (int i = 0; i <= size; i++) {
									Select.Option option;
									if(c.mask_){
										if (null != pn && pn[i].length() > 8) {
											int front = 4, last = 4;
											if (mask.length() > 4) {
												String[] an = mask.split(",");
												if ((an[1] != null || an[1].equals(""))
														&& (an[2] != null || an[2].equals(""))) {
													front = Integer.parseInt(an[1]);
													last = Integer.parseInt(an[2]);
												}
											}
											String b = pn[i].substring(0, front).concat("****")
													.concat(pn[i].substring(pn[i].length() - last));
											option = new Option(activity_, b);
										} else {
											option = new Option(activity_, pn[i]);
										}
										option.value_=pn[i];
									}else{
										option = new Option(activity_, pn[i]);
									}
									option.ref_ = "0";
									sl.setDropdownMenuText(option);
									option.setParent(sl);
								}
								sl.isCombobox_ = true;
								c.isComlexbobox_ = true;
								c.setPadding(5, 0, 25, 0);
								c.comboboxSelect_ = sl;
							}
                        }
                        hi.view_ = c;

                        c.setTag(na + textFiedCount_);
                        c.setSingleLine();
                    }
                });
                synchronized (this) {
                    while (htmlItem_.view_ == null || (!(htmlItem_.view_ instanceof mTextField))) {
                        wait(100);
                    }
                }
            } 
            setEncrypt(getAttrString("encryptMode"), htmlItem.view_);
        } else if (type.equals("label")) {
            Label temp = new Label(activity, "", false, false, false);
            temp.setFocusable(false);
            temp.delaytime_ = Integer.parseInt(getAttrString("delay"));
            temp.offset_ = getAttrString("offset");
            temp.caption_ = getAttrString("caption");
            temp.setTag(name);
            temp.relaDismiss_ = Utils.string2Array(getAttrString("dismiss"), ",");
            temp.relaUnfocusable_ = Utils.string2Array(getAttrString("unfocusable"), ",");
            setEncrypt(getAttrString("encryptMode"), temp);
            htmlItem.view_ = temp;
            activity.countLabel_ = temp; // 待议
        } else if (type.equals("radio")) {
            String checked = getAttrString("selected");
            String selectSort = getAttrString("sort");
            String sortKey = getAttrString("sortkey");
            String tempvalue = getAttrString("value");
            String[] relaEnable = Utils.string2Array(getAttrString("enable"), ",");
            String[] relaDisable = Utils.string2Array(getAttrString("disable"), ",");
            String[] relaVisible = Utils.string2Array(getAttrString("visible"), ",");
            String[] relaInvisible = Utils.string2Array(getAttrString("invisible"), ",");
            
            final Radio temp = Radio.createRadio(activity, htmlItem.textInForm_, null, name, selectSort, sortKey);
            temp.attrName_ = name;
            temp.attrValue_ = value;
            temp.attrSegment_ = getAttrString("segment");
            temp.time_ = getAttrString("time");
            if (temp.time_ != null) {//如果等于null，那么说明这个radio不是用来控制自动刷新的，也就不用去改变控制是否自动更新的变量
    			BaseView.wantToUpdateTable_ = temp.time_;
    		}
         // 该属性执行与attrSegment_属性同样效�?只是由于iphone手机的开关为?��动效�?android暂时不实???
            if (null == temp.attrSegment_)
                temp.attrSegment_ = getAttrString("switch");
            temp.attrReitem = getAttrString("reitem");
            temp.attrSearchkey_ = getAttrString("searchkey");
            temp.backValue_ = backValue;
            if (null != tempvalue && tempvalue.contains("yes")) {
                temp.attrSave_ = true;
            } else{
            	temp.attrSave_ = false;
            }
            temp.relaEnable_ = relaEnable;
            temp.relaDisable_ = relaDisable;
            temp.relaVisible_ = relaVisible;
            temp.relaInvisible_ = relaInvisible;
            temp.setTag(name);
            if (stack_.contains("form")) {
                // 由于Form控件涉及到联动，但android界面等级有限，现在有一部分控件在xml中是属于form的内层结构，
                // 但是却没有被添加到form管理器中。所以通过这种方法来矫正未放到form管理器中的控件联动
                temp.setForm(htmlItem_.formLayout_);
            }
            setEncrypt(getAttrString("encryptMode"), temp);
            if (null != temp.attrSegment_) {
                if (temp.attrSegment_.equalsIgnoreCase("yes")) {
                    if (null == sll_) {
                        sll_ = new SegmentLinearLayout(activity, temp.attrName_);
                    } else if (!sll_.segMentName_.equalsIgnoreCase(temp.attrName_)) {
                        // 查看xml中是否有多个segmengt控件,如果是则重新new一个segment控件
                        sll_ = null;
                        sll_ = new SegmentLinearLayout(activity, temp.attrName_);
                    }
                    // 如果单选按??�的该属性为“yes”，则记�?该属性出现�?�序�??��?��时序号总�?1
                    // 先得到管理器的集合大�?
                    sll_.addView(temp);
                    temp.segmentIndex_ = sll_.getChildCount();
                    // 表示该管理器已经在界面管理器�?
                    htmlItem.view_ = sll_;
                    ParseHtml.applyCssOnComponent(temp, htmlItem_.peekStyle(), htmlItem_.nodeStyles_);
                }
            } else {
                htmlItem.view_ = temp;
            }
			
            // 设置默认选项********************************************************************
            if (checked != null) {
                temp.setCheckedManually(true);
            } else if (htmlItem_.getSelectRadio(activity_, temp) == null) {
                temp.setCheckedManually(true); // if no default select, make it as
            }

            if (null != temp.attrName_ && null != htmlItem_ && null != htmlItem_.ls_ && null != htmlItem_.ls_.faction_
                    && null != htmlItem_.ls_.faction_.name_ && null != htmlItem_.ls_.faction_.action_) {
                String isSelected = (String) Mid.savePropertyTemp_.get(htmlItem_.ls_.faction_.name_.concat(htmlItem_.ls_.faction_.action_).concat(temp.attrName_));
                if (null != isSelected && isSelected.equalsIgnoreCase("true")) {
                    temp.setCheckedManually(true);
                }
            }

            if (null != temp.attrSearchkey_) {
            	// 如果单选按钮控件存在searchkey属性，则该控件再添加入界面的时候设置为非选择
                temp.setChecked(false);
            }
            // 设置单选按钮的控件联动
            if ((null != temp.relaEnable_) || (null != temp.relaDisable_) || (null != temp.relaVisible_) || (null != temp.relaInvisible_)) {
                temp.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                        temp.settleComponets(activity);
                    }

                });
            }
        } else if (type.equals("checkbox")) {
            String checked = getAttrString("checked");
            String[] relaEnable = Utils.string2Array(getAttrString("enable"), ",");
            String[] relaDisable = Utils.string2Array(getAttrString("disable"), ",");
            String[] relaVisible = Utils.string2Array(getAttrString("visible"), ",");
            String[] relaInvisible = Utils.string2Array(getAttrString("invisible"), ",");
            boolean isChecked = false;
            if (checked != null)
                isChecked = true;
            final cCheckBox temp = cCheckBox.createCheckBox(htmlItem.textInForm_, activity);
            temp.setChecked(isChecked);
            temp.attrName_ = name;
            temp.inputName_ = getAttrString("inputname");
            temp.attrValue_ = value;
            temp.relaEnable_ = relaEnable;
            temp.relaDisable_ = relaDisable;
            temp.relaVisible_ = relaVisible;
            temp.relaInvisible_ = relaInvisible;
            temp.setTag(name);
            if (stack_.contains("form")) {
                // 由于Form控件涉及到联动，但android界面等级有限，现在有一部分控件在xml中是属于form的内层结构，
                // 但是却没有被添加到form管理器中。所以通过这种方法来矫正未放到form管理器中的控件联动
                temp.setForm(htmlItem_.formLayout_);
            }
            setEncrypt(getAttrString("encryptMode"), temp);
            // if (getAttrString("encrypt") != null)
            // temp.isEncrypt_ = true;
            temp.backValue_ = backValue;
            temp.shrinkWidth();
            htmlItem.view_ = temp;
            // 设置多选按钮的�?件联动
            if ((null != temp.relaEnable_) || (null != temp.relaDisable_) || (null != temp.relaVisible_) || (null != temp.relaInvisible_)) {
                temp.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                        temp.settleComponets(activity, 0);
                    }
                });
            }
        } else if (type.equals("submit") || type.equals("reset")) {
            String noCancel = getAttrString("nocancel");
            String buttonAction = getAttrString("buttonAction");
            mButton temp = new mButton(activity, value, styleIndex, false, false, false);
            if (type.equals("submit"))
                temp.buttonType_ = "submit";
            else
                temp.buttonType_ = "reset";
            if (noCancel != null && noCancel.equals("true"))
                temp.isNoCancel_ = true;
            temp.attrName_ = name;
            temp.attrValue_ = value;
            temp.loginType_ = getAttrString("loginType");
            temp.getJson_ = getAttrString("getJson");
            temp.hangType_ = getAttrString("hangType");
            temp.setTag(name);
            if (stack_.contains("form")) {
                // 由于Form控件涉及到联动，但android界面等级有限，现在有一部分控件在xml中是属于form的内层结构，
                // 但是却没有被添加到form管理器中。所以通过这种方法来矫正未放到form管理器中的控件联动
                temp.setForm(htmlItem_.formLayout_);
            }
            setEncrypt(getAttrString("encryptMode"), temp);
            temp.buttonAction_ = buttonAction;
            htmlItem.view_ = temp;
        } else if (type.equals("button")) {
            String noCancel = getAttrString("nocancel");
            String accessory = getAttrString("accessory");
            String buttonAction = getAttrString("buttonAction");
            mButton temp = new mButton(activity, value, styleIndex, false, false, false);
            if (noCancel != null && noCancel.equals("true"))
                temp.isNoCancel_ = true;
            temp.buttonType_ = type;
            temp.attrName_ = name;
            temp.attrValue_ = value;
            temp.setTag(name);
            // 加减联动属性获取
            String linkage = getAttrString("linkage");
            String linkType = getAttrString("linkType");
            String max = getAttrString("max");
            String min = getAttrString("min");
            temp.linkage_ = linkage;
            temp.linkType_ = linkType;
            temp.maxValue_ = max;
            temp.minValue_ = min;
            setEncrypt(getAttrString("encryptMode"), temp);
            temp.accessory_ = accessory;
            temp.buttonAction_ = buttonAction;
            htmlItem.view_ = temp;
        } else if (type.equals("hidden")) {
        	if(null != name) {
                htmlItem.hidden_ = Utils.getHidden(htmlItem.hidden_, name, value);
        	}
        } else if (type.equals("display")) {
            Label label = new Label(activity, value, false, false, false);
            label.isValueLabel_ = true;
            label.attrName_ = name;
            label.attrValue_ = value;
            label.setTag(name);
            setEncrypt(getAttrString("encryptMode"), label);
            htmlItem.view_ = label;
        } else if (type.equals("date")) {
        	String align = getAttrString("align");
        	String width = getAttrString("width");
        	String height = getAttrString("height");
            DatePicker date = new DatePicker(activity, value, align, width, height);
            date.attrName_ = name;
            htmlItem.view_ = date;
        } else if (type.equals("time")) {
        	String align = getAttrString("align");
        	String width = getAttrString("width");
        	String height = getAttrString("height");
            TimePicker time = new TimePicker(activity, value, align, width, height);
            time.attrName_ = name;
            htmlItem.view_ = time;
        }
    }

    /**
     * Append the <input> component into the parent.
     * 
     * @param localName
     * @throws Exception
     */
    private void appendInputComponent(String localName) throws Exception {
        if (htmlItem_.view_ == null) {
            return;
        }
        if (inputType_.equals("text") || inputType_.equals("password")) {
            htmlItem_.textInForm_ = null;
            htmlItem_.addLsItem(activity_);
        } else if (inputType_.equals("label")) {
            Label label = (Label) htmlItem_.view_;
            label.setContentText(htmlItem_.textInForm_);
            htmlItem_.textInForm_ = null;
            htmlItem_.addLsItem(activity_);
        } else if (inputType_.equals("radio")) {
            // 如果radio控件带segment属性，则htmlItem_.view_不是radio控件，而是带segment属性radio控件的集合
            // 所有的radio控件通过以下步骤获得显示文字
            if (htmlItem_.view_ instanceof Radio) {
                Radio radio = (Radio) htmlItem_.view_;
                radio.setContentText(htmlItem_.textInForm_);
                htmlItem_.textInForm_ = null;
                htmlItem_.addLsItem(activity_);
            } else {
                SegmentLinearLayout sll = (SegmentLinearLayout) htmlItem_.view_;
                // 由于该方法是关闭input节点时调用，所以管理器里面最后一个元素为需要设置显示文本的控件
                Radio radio = (Radio) sll.getChildAt(sll.getChildCount() - 1);
                radio.setContentText(htmlItem_.textInForm_);
                htmlItem_.textInForm_ = null;
                if (!sll.isAdded_) {
                	// 如果该管理器已被添加,该标志为真
                    htmlItem_.addLsItem(activity_);
                    sll.isAdded_ = true;
                } else {
                    htmlItem_.view_ = null;
                }
            }
        } else if (inputType_.equals("checkbox")) {
            cCheckBox checkBox = (cCheckBox) htmlItem_.view_;
            checkBox.setContentText(htmlItem_.textInForm_);
            checkBox.shrinkWidth();
            htmlItem_.textInForm_ = null;
            htmlItem_.addLsItem(activity_);
        } else if (inputType_.equals("submit") || inputType_.equals("reset") || inputType_.equals("button")) {
            htmlItem_.textInForm_ = null;
            htmlItem_.addLsItem(activity_);
        } else if (inputType_.equals("display")) {
            htmlItem_.textInForm_ = null;
            htmlItem_.addLsItem(activity_);
        } else if (inputType_.equals("elevator")) {
            htmlItem_.textInForm_ = null;
            htmlItem_.addLsItem(activity_);
        }

        inputType_ = "";
    }

    private void setEncrypt(String encrypt, Component cmp) {
        cmp.setEncrypt(encrypt);
    }

    /**
     * Parser CSS in Line. We support only the following attributes and values: color, background-color, text-align,
     * vertical-align, font-style, font-weight, font-size.
     */
    private void parserCSSInLine(String localName, ParseHtml.LayoutState ls, int isEndTag) throws Exception {

        if (isEndTag == END_TAG) {
            ls.setDefaultLayoutState();
        } else {
            String strVal = getAttrString("style");
            if (strVal != null) {
                int index = 0;
                char ch = ';';

                String color = Utils.getXMLResponseAttribute(strVal, "color:", index, ch);
                if (color != null) {
                    ls.prevColor = ls.color_;
                    ls.color_ = Utils.getColorFromString(color);
                }

                String bgColor = Utils.getXMLResponseAttribute(strVal, "background-color:", index, ch);
                if (bgColor != null) {
                    ls.hasBackgroundColor_ = true;
                    ls.backgroundColor_ = Utils.getColorFromString(bgColor);
                }
                String fStyle = Utils.getXMLResponseAttribute(strVal, "font-style:", index, ch);
                if (fStyle != null) {
                    if (fStyle.toLowerCase().equals("italic")) {
                        ls.isItalic_ = true;
                    }
                }

                String fWeight = Utils.getXMLResponseAttribute(strVal, "font-weight:", index, ch);
                if (fWeight != null) {
                    if (fWeight.toLowerCase().equals("bold")) {
                        ls.isBold_ = true;
                    }
                }

                String fSize = Utils.getXMLResponseAttribute(strVal, "font-size:", index, ch);
                if (fSize != null) {
                    if (fSize.toLowerCase().equals("medium")) {
                        ls.fontSize_ = ConfigManager.SIZE_MEDIUM;
                    } else if (fSize.toLowerCase().equals("large")) {
                        ls.fontSize_ = ConfigManager.SIZE_LARGE;
                    }
                }
                ls.font_ = new Paint();
            }
        }
    }

    Vector<POI> getPoiVector() {
        return poiList_;
    }

    /**
     * @param attrName
     * @return
     */
    private final String getAttrString(String attrName) {
        String attr = null;
        try {
            attr = Utils.insteadOfSpecillCharacter(atts_.getValue(attrName), false);
        } catch (Exception e) {
            Utils.printException(e);
        }
        return attr;
    }

    /**
     * @param atts
     * @param attrName
     * @return
     */
    private final String getAttrString(Attributes atts, String attrName) {
        String attr = null;
        try {
            attr = Utils.insteadOfSpecillCharacter(atts.getValue(attrName), false);
        } catch (Exception e) {
        	Utils.printException(e);
        }
        return attr;
    }
    
    
    /**
     *  清空资源
     */
    public void dispose() {
        buf_ = null;
        if (stack_ != null)
            stack_.clear();
        stack_ = null;
        ls_ = null;
        if (poiList_ != null)
            poiList_.clear();
        poiList_ = null;
        if (options_ != null)
            options_.clear();
        options_ = null;
        htmlItem_ = null;
        if (mid_.cacheDivs != null)
            mid_.cacheDivs.clear();
        mid_.cacheDivs = null;
        if (mid_.cacheDivStyles_ != null)
            mid_.cacheDivStyles_.clear();
        mid_.cacheDivStyles_ = null;
        System.gc();
    }
}

